/*
 * This file manage the logic of import product.
 * The logic here is okay, the interface needs a litter ajustment
 */
Ext.require([ '*' ]);

/**
 * ===============Will be replaced later if have better solution=====start============
 */
var productArr = [];
Ext.Ajax.request({
	   url: 'rest/universal/getContent?type=product',
	   method: "GET",
       async: false, 
	   success: function(response){
		   products =  response.responseText;
	   }
});

var locationArr = [];
Ext.Ajax.request({
	   url: 'rest/universal/getContent?type=storageLocation',
	   method: "GET",
       async: false, 
	   success: function(response){
		   locationArr  = response.responseText;
	   }
});

var transportArr = [];
Ext.Ajax.request({
	   url: 'rest/universal/getContent?type=transport',
	   method: "GET",
       async: false, 
	   success: function(response){
		   transportArr  = response.responseText;
	   }
});
/**
 * ===============Will be replaced later if have better solution====end=============
 */


/* define a store structure for import product */
Ext.define('Storage.import.Store', {
	extend : 'Ext.data.Store',
	fields : [ 'customerId', 'product', 'batchNo', 'storage', 'quantity', 'plateNo', 'productFrom', 'transport', 'importTime' ],
	proxy : {
		type : 'memory',
		reader : {
			type : 'json',
			root : 'items'
		}
	}
});

Ext.define('Storage.product.borrow.Store', {
	extend : 'Ext.data.Store',
	storeId : 'simpsonsStore',
	fields : [ 'productFrom', 'productTo', 'product', 'batchNo', 'quantity', 'actionTime' ],
	autoLoad : 'false'
});

/* define a table structure structure for import product */
Ext.define('Storage.import.Table', {
	extend : 'Ext.grid.Panel',
	id : 'productImportPanel',
	store : new Storage.import.Store(),
	height : 450,
	width : 950,
	columns : [ {
		text : 'Customer ID',
		dataIndex : 'customerId',
		flex : 1
	}, {
		text : 'Product Type',
		dataIndex : 'product',
		flex : 1
	}, {
		text : 'Batch',
		dataIndex : 'batchNo',
		flex : 1
	}, {
		text : 'Storage',
		dataIndex : 'storage',
		flex : 1
	}, {
		text : 'Quantity',
		dataIndex : 'quantity',
		flex : 1
	}, {
		text : 'Plate No',
		dataIndex : 'plateNo',
		flex : 1
	}, {
		text : 'From',
		dataIndex : 'productFrom',
		flex : 1
	}, {
		text : 'Transport',
		dataIndex : 'transport',
		flex : 1
	}, {
		text : 'Import Time',
		dataIndex : 'importTime',
		flex : 1
	} ]
});

/* Define a controller to control the create of Import Controller */
function ImportProductController() {
	
}

// create product import condition panel
ImportProductController.prototype.createHeader = function() {
	var conditionPanel = Ext.create('Ext.panel.Panel',{
		id : 'operationOfProductInStore',
		layout : 'hbox',
		items : [{
					xtype : 'container',
					layout : 'vbox',
					items : [ {
						xtype : 'textfield',
						id : 'customerId',
						fieldLabel : 'Customer ID',
						allowBlank : false
					}, {
						xtype : 'textfield',
						id : 'storage',
						fieldLabel : 'Storage',
						vtype : 'email'
					}, {
						xtype : 'combo',
						id : "productStartPoint",
						fieldLabel : 'From',
						store : ['location1','location2'],//locationArr,
						queryMode : 'local',
						displayField : 'name',
						valueField : 'abbr',
					} ]
				},
				{
					xtype : 'container',
					layout : 'vbox',
					items : [ {
						xtype : 'combo',
						id : 'productType',
						fieldLabel : 'Product Type',
						store : ['apt1','apt2'],
						queryMode : 'local',
						displayField : 'q',
						valueField : 'abbr',
					}, {
						xtype : 'numberfield',
						id : 'quantity',
						fieldLabel : 'Quantity',
						allowNegative : false,
						minValue : 1,
						hideTrigger : true,
						allowBlank : false
					}, {
						id : 'transport',
						xtype : 'combo',
						fieldLabel : 'Transport',
						store : ['c','d'],
						queryMode : 'local',
						displayField : 'q',
						valueField : 'abbr',
					} ]
				},
				{
					xtype : 'container',
					layout : 'vbox',
					items : [{
								xtype : 'textfield',
								id : 'batchNo',
								fieldLabel : 'Batch No',
								allowBlank : false
							}, {
								id : 'plateNo',
								xtype : 'textfield',
								name : 'name',
								fieldLabel : 'Plate No',
								allowBlank : false
							}, {
								id:'importProductsDate',
								xtype : 'datefield',
								anchor : '100%',
								fieldLabel : 'Import Date'
							}, {
								xtype : 'container',
								layout : 'hbox',
								items : [{
											xtype : 'button',
											text : 'Add:    ',
											listeners : {
												click : function(b, e) {
													var rowData = {
														"customerId" : Ext.getCmp('customerId').getValue(),
														"product"  : Ext.getCmp('productType').getValue(),
														"batchNo" : Ext.getCmp('batchNo').getValue(),
														"storage" : Ext.getCmp('storage').getValue(),
														"quantity" : Ext.getCmp('quantity').getValue(),
														"plateNo" : Ext.getCmp('plateNo').getValue(),
														"transport" : Ext.getCmp('transport').getValue(),
														"productFrom" : Ext.getCmp('productStartPoint').getValue(),
														"importTime" : Ext.Date.format(Ext.getCmp('importProductsDate').getValue(),'Y-m-d')
													};
													if( rowData.customerId==""  || rowData.product=="" || rowData.batchNo=="" ||
														rowData.storage ==""    || rowData.quantity=="" || rowData.transport==""|| 
														rowData.productFrom=="" || rowData.importTime == "" || rowData.plateNo==""){
														Ext.Msg.alert("", 'All fields can not be empty', null);
														return ;
													}
													var store = Ext.getCmp("productImportPanel").getStore();
													store.insert(store.getCount(),rowData);
												}
											}
										},
										{
											xtype : 'button',
											text : 'Delete: ',
											listeners : {
												click : function(b, e) {													
													var store = Ext.getCmp("productImportPanel").getStore();
													var selectedRecord = Ext.getCmp("productImportPanel").getSelectionModel().getSelection()[0];
													var row = store.indexOf(selectedRecord);
													store.removeAt(row);
												}
											}
										} ]
							} ]
				} ]
			});
	return conditionPanel;
}

// Create import product table
ImportProductController.prototype.createBody = function() {
	var importTable = Ext.create('Ext.panel.Panel', {
		id : 'importProductTable',
		items : [ new Storage.import.Table() ]
	});
	return importTable;
}

// Create import product table
ImportProductController.prototype.createBottom = function() {
	var bottomToolbar = Ext.create('Ext.button.Button', {
		id : 'importTableFootBar',
		text : 'Submit',
		listeners : {
			click : function(b, e) {
				var store = Ext.getCmp("productImportPanel").getStore();
				if(store.getCount() == 0){
					Ext.Msg.alert("", 'Please add data first', null);
					return;
				}
				Ext.Msg.confirm('', "Do you want to submit?", function(btn,text) {
					if (btn == 'yes') {
						var successCount = 0;
				    	for(var index = 0; index<store.getCount(); index++){
				    		var data = store.getAt(index).getData();
				    		var rowData = {"importFrom":data.productFrom,"transport":data.transport, "customerId":data.customerId, "plateNo":data.plateNo, "storage":data.storage, "batchNo":data.batchNo, "product":data.product, "quantity":data.quantity, "importTime":data.importTime};
				    		Ext.Ajax.request({
				    			url: 'rest/import/add_record',
				    			method: 'POST',
				    			async: false,
				    			jsonData: rowData,
				    			success: function() {
				    				successCount = successCount + 1;
				    				if(successCount == store.getCount()){
								    	Ext.Msg.alert("", 'Submit Successfully', null);
								    	store.removeAll();
				    				}
				    			},
				    			failure: function() {
				    				Ext.Msg.alert("", 'Submit Failed', null);
				    			}
				    		});
				    	}

					}
				});
			}
		}
	});
	return bottomToolbar;
}

/* End of define Import controller */
